//
//  RefreshAssist.m
//  for_test
//
//  Created by Carlson Lee on 2017/4/26.
//  Copyright © 2017年 Carlson Lee. All rights reserved.
//

#import "RefreshAssist.h"

@interface RefreshAssist ()
{
    
}

@property(nonatomic, copy)void(^block)();
@property(nonatomic, assign)NSInteger requestNum;
@property(nonatomic, strong)NSTimer* timer;

@end

static RefreshAssist* refresh;
@implementation RefreshAssist

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        refresh = [[RefreshAssist alloc]init];
    });
    return refresh;
}

+ (void)startWithRequsts:(NSInteger )num timeOut:(NSInteger )time block:(void(^)())block
{
    RefreshAssist* ra = [[RefreshAssist alloc]initWithStartWithReqs:num timeOut:time];
    ra.block = block;
    
}

- (instancetype)initWithStartWithReqs:(NSInteger )num timeOut:(NSInteger )time
{
    if(self = [super init]){
        [self startWithReqs:num timeOut:time];
    }
    return self;
}

- (void)startWithReqs:(NSInteger )num timeOut:(NSInteger )time
{
    _requestNum = num;
    if(!_timer){
        _timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(handleTime) userInfo:nil repeats:NO];
    }
}

- (void)handleTime
{
    if(_block)_block();
}

- (void)handleOver
{
    if(self.requestNum){
        self.requestNum--;
    }
    if(self.requestNum<=0){
        if([_timer isValid]){
            [_timer invalidate];
            _timer = nil;
        }
        [self handleOver];
    }
}

@end
